package com.xian.ucenter.controller.admin;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xian.ucenter.commons.Result;
import com.xian.ucenter.entities.Link;
import com.xian.ucenter.service.impl.LinkServiceImpl;
import com.xian.ucenter.utils.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xian
 * @since 2022/07/23 02:59
 */
@RestController
@RequestMapping("/ucenter/admin/link")
public class LinkController {
    @Autowired
    private LinkServiceImpl linkService;
    @Resource
    private PageUtil<Link> postPageUtil;

    @PostMapping("/save")
    public Result save (@RequestBody Link link) {
        return linkService.updateById(link)?Result.ok():Result.fail();
    }

    @PostMapping("/create")
    public Result create (@RequestBody Link link) {
        System.out.println("");
        return linkService.save(link) ? Result.ok():Result.fail();
    }

    @GetMapping("/{linkId}")
    public Result getLink (@PathVariable("linkId") String linkId) {
        Link link = linkService.getById(linkId);
        if (ObjectUtil.isNull(link))
            throw new RuntimeException("链接不存在");
        return Result.ok("link",link);
    }

    @PostMapping("/search/{current}/{count}")
    public Result getLink (@PathVariable("current") Integer current, @PathVariable("count") Integer count, @RequestBody(required = false) Link link) {
        QueryWrapper<Link> linkQueryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(link)) {
            String title = link.getTitle();
            String description = link.getDescription();
            Date begin = link.getCreateTime();
            Date end = link.getModifyTime();
            if (StringUtils.hasText(title)) {
                linkQueryWrapper.like("title",title);
            } else if (StringUtils.hasText(description)) {
                linkQueryWrapper.eq("description",description);
            } else if (ObjectUtil.isNotNull(begin)) {
                linkQueryWrapper.lt("create_time",begin);
            } else if (ObjectUtil.isNotNull(end)) {
                linkQueryWrapper.gt("create_time",end);
            }
        }
        return postPageUtil.pageList(current,count,linkService,linkQueryWrapper);
    }

    @GetMapping("/del/{linkId}")
    public Result delLink (@PathVariable("linkId") String linkId) {
        return linkService.removeById(linkId)?Result.ok():Result.fail();
    }
}
